package controller.login;

import DateTools.DateUtil;
import domain.entity.ExecutionLog;
import domain.entity.base.MaintainBaseInfo;
import domain.entity.base.UserInfo;
import domain.service.base.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import util.HttpRequestUtil;
import util.WebContextUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by bowen on 2016/7/28.
 */
@Controller
@RequestMapping(value = "/define")
public class DefineInterfaceController {

    private static final Logger logger = LoggerFactory.getLogger(DefineInterfaceController.class);

    @Autowired
    private TunnelBaseService tunnelBaseService;
    @Autowired
    private TunnelCompanyService tunnelCompanyService;
    @Autowired
    private MaintainBaseService baseService;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ExecutionLogService executionLogService;

    @RequestMapping(value = "getBaseStatistics")
    @ResponseBody
    public Map<String, Object> getBaseStatistics(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("baseNumber", 67);//基础设施
        resultMap.put("companyNumber", tunnelCompanyService.getTunnelCompanyCount()); //养护公司
        resultMap.put("tunnelBaseNumber", tunnelBaseService.getTunnelBaseCount()); //养护基地
        resultMap.put("planNumber", ""); //当日养护计划数
        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getPlanToday", null);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    JSONObject object = jsonObject.getJSONObject("result");
                    JSONArray array = object.getJSONArray("total");
                    JSONObject obj = (JSONObject) array.get(0);
                    resultMap.put("planNumber", obj.getInt("count"));
                } else {
                    System.out.println("返回数据异常！" + jsonObject.toString());
                }
            }
        }
        int carNumber = 0;
        JSONObject jsonObjectCar = HttpRequestUtil.sendClientRequest("getCarFacInfo", null);
        if (jsonObjectCar != null) {
            if (jsonObjectCar.containsKey("code")) {
                if (jsonObjectCar.getInt("code") == 0) {
                    JSONArray array = jsonObjectCar.getJSONArray("result");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        if (!"".equals(obj.getString("equipm_amount"))) {
                            carNumber += Integer.parseInt(obj.getString("equipm_amount"));
                        }
                    }
                }
            }
        }
        resultMap.put("carNumber", carNumber); //养护基地
        return resultMap;
    }

    /**
     * 获取当日养护计划
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getPlanToday")
    @ResponseBody
    public Map<String, Object> getPlanToday(@RequestParam(value = "page", defaultValue = "") String page, @RequestParam(value = "perpage", defaultValue = "") String perpage, @RequestParam(value = "complete_status", defaultValue = "") String complete_status, @RequestParam(value = "projecttype", defaultValue = "") String projecttype, @RequestParam(value = "roadclosure", defaultValue = "") String roadclosure, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        complete_status = new String(complete_status.getBytes("ISO-8859-1"), "UTF-8");
        projecttype = new String(projecttype.getBytes("ISO-8859-1"), "UTF-8");
        roadclosure = new String(roadclosure.getBytes("ISO-8859-1"), "UTF-8");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        UserInfo userInfo = userInfoService.getUserInfoById(userId);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        JSONArray array = new JSONArray();
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        int page_ = 1, perpage_ = 10;
        if (!"".equals(page)) {
            page_ = Integer.parseInt(page);
        }
        if (!"".equals(perpage)) {
            perpage_ = Integer.parseInt(perpage);
        }
        parameterMap.put("page", page_);
        parameterMap.put("perpage", perpage_);
        if (!"".equals(complete_status) || !"".equals(projecttype) || !"".equals(roadclosure)) {
            if (!"".equals(complete_status)) {
                HashSet status = new HashSet();
                String[] complete_status_array = complete_status.split(",");
                for (String statusTxt : complete_status_array) {
                    if (!"".equals(statusTxt)) {
                        status.add(statusTxt);
                    }
                }
                parameterMap.put("complete_status", status);
            }

            if (!"".equals(projecttype)) {
                HashSet type = new HashSet();
                String[] projecttype_array = projecttype.split(",");
                for (String typeTxt : projecttype_array) {
                    if (!"".equals(typeTxt)) {
                        type.add(typeTxt);
                    }
                }
                parameterMap.put("projecttype", type);
            }

            if (!"".equals(roadclosure)) {
                HashSet road = new HashSet();
                String[] roadclosure_array = roadclosure.split(",");
                for (String roadTxt : roadclosure_array) {
                    if (!"".equals(roadTxt)) {
                        road.add(roadTxt);
                    }
                }
                parameterMap.put("roadclosure", road);
            }


        }
        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getPlanToday", parameterMap);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    System.out.println("返回数据成功！" + jsonObject.toString());
                    JSONObject object = jsonObject.getJSONObject("result");
                    array = object.getJSONArray("result");
                    JSONArray totalArray = object.getJSONArray("total");
                    JSONObject totalMap = (JSONObject) totalArray.get(0);
                    resultMap.put("total", totalMap.getInt("count"));
                } else {
                    System.out.println("返回数据异常！" + jsonObject.toString());
                }
            }
        }
        resultMap.put("data", array);
        String log = "";
        String txt = "";
        if (!"".equals(complete_status)) {
            txt = "状态为：" + complete_status;
        }
        if (!"".equals(projecttype)) {
            txt = "作业类型为：" + complete_status;
        }
        if (!"".equals(roadclosure)) {
            txt = "封道为：" + complete_status;
        }
        if (userInfo != null) {
            ExecutionLog executionLog = new ExecutionLog();
            executionLog.setOpenid(userId);
            executionLog.setUsername(userInfo.getName());
            log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看当日养护列表。" + txt;
            executionLog.setExe_log(log);
            executionLogService.insert(executionLog);
        }
        return resultMap;
    }


    /**
     * 获取当日养护计划作业类型统计图
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getPlanTodayChart")
    @ResponseBody
    public Map<String, Object> getPlanTodayWorkChart(HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> resultMap = new HashMap<String, Object>();
        /****保存当日作业类型数***/
        HashSet workSetName = new HashSet();
        /****保存当日封道类型数***/
        HashSet roadSetName = new HashSet();
        /***保存当日作业类型值***/
        List<Map<String, Object>> workDataList = new ArrayList<Map<String, Object>>();
        /***保存当日封道类型值***/
        List<Map<String, Object>> roadDataList = new ArrayList<Map<String, Object>>();
        /***保存数据***/
        HashSet topSetName = new HashSet();
        /***保存当日封道类型值***/
        List<Map<String, Object>> topDataList = new ArrayList<Map<String, Object>>();
        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getPlanInfo", null);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    System.out.println("返回数据成功！" + jsonObject.toString());
                    JSONObject resultObj = jsonObject.getJSONObject("result");
                    /****获取当日作业图表**/
                    JSONArray projectArray = resultObj.getJSONArray("project");
                    for (int i = 0; i < projectArray.size(); i++) {
                        JSONObject object = projectArray.getJSONObject(i);
                        workSetName.add(object.getString("project_type"));

                        Map<String, Object> valueMap = new HashMap<String, Object>();
                        valueMap.put("name", object.getString("project_type"));
                        valueMap.put("value", object.getString("project_type_amount"));
                        workDataList.add(valueMap);
                    }

                    /****获取当日封道图表**/
                    JSONArray roadclotypeArray = resultObj.getJSONArray("roadclotype");
                    for (int i = 0; i < roadclotypeArray.size(); i++) {
                        JSONObject object = roadclotypeArray.getJSONObject(i);
                        roadSetName.add(object.getString("roadclo_type"));

                        Map<String, Object> valueMap = new HashMap<String, Object>();
                        valueMap.put("name", object.getString("roadclo_type"));
                        valueMap.put("value", object.getString("roadclo_type_amount"));
                        roadDataList.add(valueMap);
                    }

                    /*****获取养护数据*******/
                    JSONArray roadclostateArray = resultObj.getJSONArray("roadclostate");
                    for (int i = 0; i < roadclostateArray.size(); i++) {
                        JSONObject object = roadclostateArray.getJSONObject(i);
                        topSetName.add(object.getString("roadclo_state"));

                        Map<String, Object> valueMap = new HashMap<String, Object>();
                        valueMap.put("name", object.getString("roadclo_state"));
                        valueMap.put("value", object.getString("roadclo_state_amount"));
                        topDataList.add(valueMap);
                    }

                } else {
                    System.out.println("返回数据异常！" + jsonObject.toString());
                }
            }
        }
        resultMap.put("workNameArray", workSetName);
        resultMap.put("workValueArray", workDataList);
        resultMap.put("roadNameArray", roadSetName);
        resultMap.put("roadValueArray", roadDataList);
        resultMap.put("topSetName", topSetName);
        resultMap.put("topDataList", topDataList);
        JSONObject ob = JSONObject.fromObject(resultMap);
        System.out.println(ob);
        return resultMap;
    }


    /**
     * 获取车辆数目统计图
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getCarFacInfoChart")
    @ResponseBody
    public Map<String, Object> getCarFacInfoChart(HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        /***保存设施名称***/
        HashSet carSetName = new HashSet();
        /****保存数据列表****/
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getCarFacInfo", null);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    JSONArray array = jsonObject.getJSONArray("result");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        carSetName.add(obj.getString("equipm_stype"));
                        Map<String, Object> dataMap = new HashMap<String, Object>();
                        dataMap.put("value", obj.getInt("equipm_amount"));
                        dataMap.put("name", obj.getString("equipm_stype"));
                        dataList.add(dataMap);
                    }
                }
            }
        }
        resultMap.put("nameArray", carSetName);
        resultMap.put("dataList", dataList);
        return resultMap;
    }


    /**
     * 根据车辆类型查询状态
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getEquipStatus")
    @ResponseBody
    public Map<String, Object> getEquipStatus(@RequestParam(value = "carName", defaultValue = "") String carName, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        carName = new String(carName.getBytes("ISO-8859-1"), "UTF-8");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        UserInfo userInfo = userInfoService.getUserInfoById(userId);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        /***保存设施名称***/
        HashSet statusSetName = new HashSet();
        /****保存数据列表****/
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        /***保存参数**/
        Map<String, Object> parameterMap = null;
        if (!"".equals(carName)) {
            parameterMap = new HashMap<String, Object>();
            parameterMap.put("equipm_id", carName);
        }
        String log = "";
        if (userInfo != null) {
            ExecutionLog executionLog = new ExecutionLog();
            executionLog.setOpenid(userId);
            executionLog.setUsername(userInfo.getName());
            log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看车辆状态为" + carName + "的车辆信息";
            executionLog.setExe_log(log);
            executionLogService.insert(executionLog);
        }


        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getEquipStatus", parameterMap);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    JSONArray array = jsonObject.getJSONArray("result");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        statusSetName.add(obj.getString("equipm_state"));
                        Map<String, Object> dataMap = new HashMap<String, Object>();
                        dataMap.put("value", obj.getInt("equipm_s_amount"));
                        dataMap.put("name", obj.getString("equipm_state"));
                        dataList.add(dataMap);
                    }
                }
            }
        }
        resultMap.put("nameArray", statusSetName);
        resultMap.put("dataList", dataList);
        return resultMap;
    }


    /**
     * 获取养护设备数据生成设备数目图表
     *
     * @return
     */
    @RequestMapping("getBaseEquipInfoChart")
    @ResponseBody
    public Map<String, Object> getBaseEquipInfoChart(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        /****保存大型设备数目*****/
        JSONArray bigEquipmentArray = new JSONArray();
        /****保存重要物资设备数目*****/
        JSONArray materEquipmentArray = new JSONArray();
        /***保存设备数据名称***/
        HashSet equipmentSetName = new HashSet();
        /****保存设备数据列表****/
        List<Map<String, Object>> equipmentDataList = new ArrayList<Map<String, Object>>();
        Map<String, Object> parameter = new HashMap<String, Object>();
        List<MaintainBaseInfo> facilitys = baseService.getBaseBasesByCheck("facility");
        if (facilitys != null && facilitys.size() > 0) {
            String facilit[] = new String[facilitys.size()];
            for (int i = 0; i < facilitys.size(); i++) {
                facilit[i] = facilitys.get(i).getName();
            }
            parameter.put("equip", facilit);
        }
        List<MaintainBaseInfo> materiels = baseService.getBaseBasesByCheck("materiel");
        if (materiels != null && materiels.size() > 0) {
            String materiel[] = new String[materiels.size()];
            for (int i = 0; i < materiels.size(); i++) {
                materiel[i] = materiels.get(i).getName();
            }
            parameter.put("material", materiel);
        }
        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getBaseEquipInfo", parameter);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    JSONObject resultObj = jsonObject.getJSONObject("result");
                    /***设备图表数组***/
                    JSONArray array = resultObj.getJSONArray("equipm_chart_arr");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        equipmentSetName.add(obj.getString("equipm_type"));
                        Map<String, Object> dataMap = new HashMap<String, Object>();
                        dataMap.put("value", obj.getInt("equipm_num"));
                        dataMap.put("name", obj.getString("equipm_type"));
                        equipmentDataList.add(dataMap);
                    }
                    bigEquipmentArray = resultObj.getJSONArray("equipm_arr");
                    materEquipmentArray = resultObj.getJSONArray("mater_arr");
                }
            }
        }
        resultMap.put("equipmentSetName", equipmentSetName);
        resultMap.put("equipmentDataList", equipmentDataList);
        resultMap.put("bigEquipmentArray", bigEquipmentArray);
        resultMap.put("materEquipmentArray", materEquipmentArray);
        return resultMap;
    }

    /**
     * 养护基地数据下钻接口
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getEquipSubType")
    @ResponseBody
    public Map<String, Object> getEquipSubType(@RequestParam(value = "equipm_type", defaultValue = "") String equipm_type, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        equipm_type = new String(equipm_type.getBytes("ISO-8859-1"), "UTF-8");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        UserInfo userInfo = userInfoService.getUserInfoById(userId);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        /***保存设施名称***/
        HashSet statusSetName = new HashSet();
        /****保存数据列表****/
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        /***保存参数**/
        Map<String, Object> parameterMap = null;
        if (!"".equals(equipm_type)) {
            parameterMap = new HashMap<String, Object>();
            parameterMap.put("equipm_type", equipm_type);
        }
        JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getEquipSubType", parameterMap);
        if (jsonObject != null) {
            if (jsonObject.containsKey("code")) {
                if (jsonObject.getInt("code") == 0) {
                    JSONArray array = jsonObject.getJSONArray("result");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        statusSetName.add(obj.getString("equipm_stype"));
                        Map<String, Object> dataMap = new HashMap<String, Object>();
                        dataMap.put("value", obj.getInt("equipm_num"));
                        dataMap.put("name", obj.getString("equipm_stype"));
                        dataList.add(dataMap);
                    }
                }
            }
        }
        resultMap.put("nameArray", statusSetName);
        resultMap.put("dataList", dataList);
        String log = "";
        if (userInfo != null) {
            ExecutionLog executionLog = new ExecutionLog();
            executionLog.setOpenid(userId);
            executionLog.setUsername(userInfo.getName());
            log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看基地数据" + equipm_type + "的下钻信息";
            executionLog.setExe_log(log);
            executionLogService.insert(executionLog);
        }
        return resultMap;
    }

}
